from google.appengine.ext import webapp                                        
from google.appengine.ext.webapp.util import run_wsgi_app                      
import logging                                                                 
     
from StringIO import StringIO                                                  
import traceback
import xmlrpclib
from xmlrpcserver import XmlRpcServer
from google.appengine.ext import db
import datetime
from xmw import tianya
import xmw
from xmw import error
from xmw.db.counter import PostCounter

class Post_Mgr:
    
    def echo(self,msg="dd"):
        return str(msg)+"ffd"
    
    def get_lst_post(self,start,n):
        logging.info('get_lst_post,start=%d,n=%d'%(start,n))
        post_cnt=PostCounter.get_count()
        logging.info('current max post index:%d'%post_cnt)
        
        if n<0 or start <1:
            return []
        
        if n>10:
            n=10    
        p_q=tianya.Post.all()
        p_q.filter('seq >=',start)
        p_q.order('seq')
        
        lst_p=p_q.fetch(n)
        result=[]
        
        for p in lst_p:
            thread_id=p.thread_id
            thread_q =tianya.TianyaThread.all()
            #logging.info('query title of thread with thread_id:%s'%(thread_id))
            thread_q.filter('thread_id =',thread_id)
            thread=thread_q.get()
            if thread is None:
                logging.warning('THREAD NOT EXIST with thread_id:%s'%(thread_id))
                continue
            title=xmw.xmw_encoding(thread.title.encode('utf-8'))
            
            d=p.to_dict()
            d['title']=title
            result.append(d)
            logging.info('process post,\n title:%s,\n seq:%d,\n url:%s,\n date:%s'%(thread.title,p.seq,p.url,str(p.date)))
        return result
        
    def get_lst_post_info(self,start,n):
        logging.info("query post,start=%d,n=%d"%(start,n))
        if n<0 or start <1:
            logging.info("return empty post set")
            return []
        
        if n>10:
            n=10    
        p_q=tianya.Post.all()
        p_q.filter('seq >=',start)
        
        lst_p=p_q.fetch(n)
        result=[]
        
        for p in lst_p:
            result.append(p.to_dict_without_content())
        logging.info("return %d post"%len(lst_p))
        
        return result
    
    def get_post_content_by_seq(self,seq):
        p_q=tianya.Post.all()
        p_q.filter('seq =',seq)
        p=p_q.get()
        if p is None:
            return None
        else:
            return xmw.xmw_zip_encoding(p.content.encode('utf-8'))
    def get_post_content_by_seq2(self,seq):
        p_q=tianya.Post.all()
        p_q.filter('seq =',seq)
        p=p_q.get()
        if p is None:
            return None
        else:
            return xmw.xmw_encoding(p.content.encode('utf-8'))
    
    def get_seq_min(self):
        p_q=tianya.Post.all()
        #p_q.filter('seq =',seq)
        p_q.order('seq')
        p=p_q.get()
        if p is None:
            return None
        else:
            return p.seq
        
    def get_seq_max(self):
        p_q=tianya.Post.all()
        #p_q.filter('seq =',seq)
        p_q.order('-seq')
        p=p_q.get()
        if p is None:
            return None
        else:
            return p.seq

        
            
class XMLRpcHandler(webapp.RequestHandler):                                    
    rpcserver = None
                                
    def __init__(self):         
        self.rpcserver = XmlRpcServer()                                        
        post_mgr = Post_Mgr()                                                    
        self.rpcserver.register_class('post_mgr',xmw.XmlRpcWrapper(post_mgr))                               
                                                                               
    def post(self):
        request = StringIO(self.request.body)
        request.seek(0)                                                        
        response = StringIO()                                                  
        try:
            self.rpcserver.execute(request, response, None)                    
        except Exception, e:                                                   
            logging.error('Error executing: '+str(e))                          
            for line in traceback.format_exc().split('\n'):                    
                logging.error(line)
        finally:
            response.seek(0)  
                                                                               
        rstr = response.read()                                                 
        self.response.headers['Content-type'] = 'text/xml'                     
        self.response.headers['Content-length'] = "%d"%len(rstr)               
        self.response.out.write(rstr)
                                                                               
application = webapp.WSGIApplication(                                          
                                     [('/xml_rpc_service', XMLRpcHandler)],
                                     debug=True)                               
def main():
  run_wsgi_app(application)                                                    
        
if __name__ == "__main__":
    main()